#include "musiccontroller.h"


MusicController::MusicController()
{
    p_player = new QMediaPlayer();
    isPlaying = false;
    p_player->setVolume(12);
    p_player->setNotifyInterval(200);

    QObject::connect(p_player, SIGNAL(metaDataChanged()), this, SLOT(changeClientMetaData()));
    QObject::connect(p_player, SIGNAL(positionChanged(qint64)), this, SLOT(setClientPosition(qint64)));
    QObject::connect(p_player, SIGNAL(durationChanged(qint64)), this, SLOT(setClientTimeRange(qint64)));
}


MusicController::~MusicController()
{
    delete p_player;
}





void MusicController::load(QString fileUrl){
    QMediaContent v_currentTrack = QMediaContent(QUrl::fromLocalFile(fileUrl));
    p_player->setMedia(v_currentTrack);
    isPlaying = true;

    p_player->play();
    emit notifyAll("trackLoaded()");
}

/**
 * @brief MusicPlayerEngine::playPause plays or pauses the current track
 */
void MusicController::playPause()
{
    qDebug() << "PLAY/PAUSE";
    if(isPlaying){
        p_player->pause();
    } else {
        p_player->play();
    }
    isPlaying = !isPlaying;
    emit notifyAll("isPlaying(bool)", QVariantList() << true);
}





void MusicController::stop(){
    p_player->stop();
    p_player->setMedia(QMediaContent());
    isPlaying = false;
}



void MusicController::setPosition(qint64 position){
    p_player->setPosition(position);
}


void MusicController::setClientPosition(qint64 pos){
    emit notifyAll("setPosition(qint64)", QVariantList() << pos);
}

void MusicController::setClientTimeRange(qint64 duration){
    emit notifyAll("setTimeRange(int,int)", QVariantList() << 0 << (int)duration);
}


void MusicController::updateClientTimeRange(){
    emit notifyAll("setTimeRange(int,int)", QVariantList() << 0 << (int)p_player->duration());
}


void MusicController::setClientVolume(int vol){
    qint64 volume = vol;
    p_player->setVolume(volume);
    emit notifyAll("setVolume(int)", QVariantList() << vol);
}

void MusicController::changeClientMetaData(){
    QStringList keys = p_player->availableMetaData();

    QString key;
    QList<QString>::const_iterator it;
    QMap<QString, QVariant> metaMap;
    for(it = keys.constBegin(); it != keys.constEnd(); it++){
        key = *it;
        metaMap.insert(key, p_player->metaData(key));
    }
    emit notifyAll("setMetaData(QMap<QString,QVariant>)", QVariantList() << metaMap);
}
